<?php
/**
 * Created by PhpStorm.
 * User: qv
 * Date: 2018/7/12 0012
 * Time: 9:37
 */

namespace BeReborn\Base;

/**
 * Class Defer
 * @package BeReborn\Base
 */
class Defer
{

	private static $_defer = [];

	/**
	 * @param callable $callback
	 * @param array $param
	 * @param string $name
	 */
	public static function create(callable $callback, array $param,string $name)
	{
		if (!is_array($param)) {
			return;
		}
		if (!isset(static::$_defer[$name])) {
			static::$_defer[$name][] = [$callback, $param];
		} else {
			array_unshift(static::$_defer[$name], [$callback, $param]);
		}
	}

	/**
	 * @param $name
	 * 执行延后程序
	 */
	public static function trigger($name)
	{
		if (!isset(static::$_defer[$name])) {
			return;
		}
		foreach (static::$_defer[$name] as $value) {
			call_user_func($value[0], ...$value[1]);
		}
		static::clear($name);
	}

	/**
	 * @param null $name
	 */
	public static function clear($name = NULL)
	{
		if ($name != NULL) {
			static::$_defer[$name] = [];
		} else {
			static::$_defer = [];
		}
	}

	/**
	 * @param null $name
	 * @return bool
	 */
	public static function hasDefer($name = NULL)
	{
		if (empty($name) || !isset(static::$_defer[$name])) {
			return null;
		}
		return true;
	}
}
